var netWork = require('../../../utils/netWork.js');
var model = require('../../../model/model.js')
var api = require('../../../utils/api.js');
var apiCode = require('../../../utils/openApiCode.js');
const app = getApp();
var show = false;
var item = {};
var addressInfo = {};
var isClick = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl: getApp().globalData.imagesUrl,
    address: '请选择地区：',
    color: false,
    formValue: {},
    item: {
      show: show
    },
    type: '',
    addressMsg: '',
    next: "", //接下来继续领取的奖品
    isShowSelectPrize: false, //是否选择礼物
    choosePrize: "", //选择的奖
    source: "" //兑奖来源，1-正常流程兑奖（需要那4个参数）2-中奖记录兑奖（不需要那4个参数）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    console.log('topHeight:'+topHeight)
    console.log(options)
    this.setData({
      topHeight: topHeight,
      index: options.index,
      source: options.source,
      icon:wx.getStorageSync('productType')==4?'xinyouranPage/loading_logo':'common/loading',
    })
    let prizeL = JSON.parse(options.prizeInfo);
    this.setData({
        productType: prizeL.productType 
      })
    if (options.source == '') { //中奖记录进入
      // if (options.type == 'updateMatter') { //修改订单
      //   this.setData({
      //     type: 'updateMatter'
      //   })
      // }
      // this.setData({
      //   source: options.source,
      //   prizeOrderId: prizeL.prizeOrderId,
      //   prizeId: prizeL.prizeId
      // })
      // //更新收货信息
      // if (prizeL.materialInfo) {
      //   this.setData({
      //     materialInfo: prizeL.materialInfo,
      //     address: prizeL.materialInfo.receiveProvinceName + ' ' + prizeL.materialInfo.receiveCityName + ' ' + prizeL.materialInfo.receiveDistrictName,
      //     color: true
      //   })
      //   this.setData({
      //     addressMsg: this.data.materialInfo.receiveAddress
      //   })
      //   addressInfo = this.data.materialInfo;
      // } else { //如果中奖记录没有收货信息，看本地存储是否有值
      //   let m = wx.getStorageSync('materialInfo');
      //   if (m) {
      //     this.setData({
      //       materialInfo: m,
      //       address: m.receiveProvinceName + ' ' + m.receiveCityName + ' ' + m.receiveDistrictName,
      //       color: true,
      //       addressMsg: m.receiveAddress
      //     })
      //   } else {
      //     let nickName = wx.getStorageSync('nickName');
      //     let userPhone = wx.getStorageSync('userPhone');
      //     console.log('nickName==' + nickName);
      //     console.log('userPhone==' + userPhone);
      //     let m1 = {};
      //     if (nickName != "" && nickName != null && nickName != undefined) {
      //       m1['receiveName'] = nickName;
      //     }
      //     if (userPhone != "" && userPhone != null && userPhone != undefined) {
      //       m1['receivePhone'] = userPhone;
      //     }
      //     this.setData({
      //       materialInfo: m1
      //     })
      //   }
      //   addressInfo = this.data.materialInfo;
      // }
    } else { //正常流程进入
      let newList = []; //构建新数组，增加status(是否勾选)

      if (prizeL.prizeTypeId == undefined || prizeL.prizeTypeId == '') { //多选一
        // for (var item in prizeL.schemeList) {
        //   if (item.prizeTypeId != 8) {
        //     var newItem = prizeL.schemeList[item];
        //     newItem['status'] = false;
        //     newList.push(newItem)
        //   }
        // }
        // this.setData({
        //   chooseList: newList,
        //   isShowSelectPrize: true //选择礼品
        // })
      }
      this.setData({
        prizeOrderId: prizeL.prizeOrderId,
        prizeId: prizeL.prizeId,

      })
      //判断是否存在C奖
      if (options.next && options.next != "") {
        this.setData({
          next: JSON.parse(options.next)
        })
      }
      if (this.data.materialInfo != null) {
        this.setData({
          address: this.data.materialInfo.receiveProvinceName + ' ' + this.data.materialInfo.receiveCityName + ' ' + this.data.materialInfo.receiveDistrictName,
          color: true
        })
      }

      let m = wx.getStorageSync('materialInfo');
      if (m) {
        this.setData({
          materialInfo: m,
          address: m.receiveProvinceName + ' ' + m.receiveCityName + ' ' + m.receiveDistrictName,
          color: true,
          addressMsg: m.receiveAddress
        })
        addressInfo = this.data.materialInfo;

      } else {
       // let nickName = wx.getStorageSync('materialInfo.receiveName');
        let userPhone = wx.getStorageSync('userPhone');
        let m1 = {};
        // if (nickName != "" && nickName != null && nickName != undefined) {
        //   m1['receiveName'] = nickName;
        // }
        if (userPhone != "" && userPhone != null && userPhone != undefined) {
          m1['receivePhone'] = userPhone;
        }
        this.setData({
          materialInfo: m1
        })
      }
    }


  },
  analysisArea(e) {
    this.isLoading(true, "正在获取位置...");
    const that = this;
    //获取地理位置
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        //存入地址
        let latitude = res.latitude;
        let longitude = res.longitude;
        //解析地址
        netWork.POST('xhtx/little/analysisArea', {
          data: {
            prizeOrderId: that.data.prizeOrderId,
            latitude: latitude, //纬度
            longitude: longitude //经度
          },
          success: function (res) {
            that.isLoading(false);
            if (res.data.retCode == "0000") {
              that.setData({
                color: true,
                address: res.data.data.province + ' ' + res.data.data.city + ' ' + res.data.data.district
              });
              if (res.data.data.province != '' && res.data.data.city != '' && res.data.data.district != '') {
                //获取id
                var address = {};
                address['a'] = res.data.data.province;
                address['b'] = res.data.data.city;
                address['c'] = res.data.data.district;
                //请求数据
                model.updateAreaData(that, 0, e, address);
                addressInfo = {
                  "receiveProvinceId": that.data.item.provinces['0'].id,
                  "receiveCityId": that.data.item.citys['0'].id,
                  "receivceDistrictId": that.data.item.countys['0'].id,
                  "receiveProvinceName": res.data.data.province,
                  "receiveCityName": res.data.data.city,
                  "receiveDistrictName": res.data.data.district
                };
              }
            }

          },
          fail: function (res) {
            that.isLoading(false);
          }
        });
      },
      fail: res => {
        //失败，不去解析省市区
        that.isLoading(false);
      }
    })
  },

  //生命周期函数--监听页面初次渲染完成
  onReady: function (e) {
    // api.cancelLoading();
    //根据经纬度，获取省市区
    if (this.data.address == "" || this.data.address == '请选择省/市/区') {
      this.analysisArea(e);
    } else {
      var that = this;
      //请求数据
      model.updateAreaData(that, 0, e);
    }
  },
  //点击选择城市按钮显示picker-view
  translate: function (e) {
    console.log('点击了')
    model.animationEvents(this, 0, true, 400);
  },
  //隐藏picker-view
  hiddenFloatView: function (e) {
    model.animationEvents(this, 200, false, 400);
    if (e.target.dataset.id == '555') {
      return;
    }
    if (this.data.address == '请选择省/市/区' || JSON.stringify(addressInfo) == '{}' || (this.data.item.value[0] == 0 && this.data.item.value[1] == 0 && this.data.item.value[2] == 0)) {
      addressInfo = {
        "receiveProvinceId": '110000',
        "receiveCityId": '110100',
        "receivceDistrictId": '110101',
        "receiveProvinceName": '北京市',
        "receiveCityName": '北京市',
        "receiveDistrictName": '东城区'
      };

    }
    this.setData({
      address: addressInfo.receiveProvinceName + ' ' + addressInfo.receiveCityName + ' ' + addressInfo.receiveDistrictName,
      color: true
    })

  },
  //滑动事件
  bindChange: function (e) {
    model.updateAreaData(this, 1, e);
    item = this.data.item;
    addressInfo = {
      "receiveProvinceId": item.provinces[item.value[0]].id,
      "receiveCityId": item.citys[item.value[1]].id,
      "receivceDistrictId": item.countys[item.value[2]].id,
      "receiveProvinceName": item.provinces[item.value[0]].name,
      "receiveCityName": item.citys[item.value[1]].name,
      "receiveDistrictName": item.countys[item.value[2]].name
    };
  },

  /**
   * 点击领取,进行实物奖兑奖
   */
  revicePrize: function () {


    this.isLoading(true, "正在提交...");
    const that = this;
    //兑奖
    netWork.POST('receiveMatter', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: that.data.prizeOrderId,
        prizeId: that.data.prizeId,
        positioningStyle: wx.getStorageSync('positioningStyle'),
        positioningType: wx.getStorageSync('positioningType'),
        latitude: wx.getStorageSync('latitude'),
        longitude: wx.getStorageSync('longitude'),
        speed: wx.getStorageSync('speed'),
        accuracy: wx.getStorageSync('accuracy'),
        receiveName: that.data.formValue.userName, //收货人
        receivePhone: that.data.formValue.phone, //收货电话
        receiveProvinceId: addressInfo.receiveProvinceId, //省
        receiveCityId: addressInfo.receiveCityId, //市
        receivceDistrictId: addressInfo.receivceDistrictId, //区
        receiveProvinceName:addressInfo.receiveProvinceName,
        receiveCityName: addressInfo.receiveCityName,
        receiveDistrictName: addressInfo.receiveDistrictName,
        receiveAddress: that.data.formValue.detailAddress, //地址
        source: that.data.source, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
      },
      success: function (res) {
        that.isLoading(false);
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 3000
          })
          setTimeout(function () {
            let newPrizeList = [];
            let prize = {};
            if (that.data.source == 1) {
              if (that.data.choosePrize != '') {
                //正常流程，更新list
                prize = that.data.choosePrize;
                console.log(prize)
                newPrizeList = wx.getStorageSync('prizeList')
                console.log(newPrizeList[that.data.index])
                if (newPrizeList != null) {
                  newPrizeList[that.data.index] = prize;
                  newPrizeList[that.data.index].status = '8'; //更新为领取成功
                  console.log(newPrizeList)

                  wx.setStorageSync('prizeList', newPrizeList)
                }
              } else {
                //更新缓存中的prizeList
                console.log("非多选一")
                newPrizeList = wx.getStorageSync('prizeList');
                console.log(newPrizeList)
                newPrizeList[that.data.index].status = '8'; //更新为领取成功
                wx.setStorageSync('prizeList', newPrizeList)
              }
              let pages = getCurrentPages(); //当前页面
              let prevPage = pages[pages.length - 2]; //上一页面
              prevPage.setData({ //直接给上移页面赋值
                prizeList: wx.getStorageSync('prizeList'),
              });
              that.handlerGobackClick();
            } else {
              //跳转中记录
              wx.redirectTo({
                url: '../../prizeRecord/prizeRecord',
              })
            }

          }, 1000)
        } else if (res.data.retCode == "10052") {
          setTimeout(function () {
            wx.showToast({
              title: '收货信息不支持表情等特殊字符，请修改后再提交哦~',
              icon: 'none',
              duration: 3000
            })
          }, 100)
        } else {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          })
        }

      },
      fail: function (res) {
        that.isLoading(false);
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
        })
      }
    });
  },
  //表单提交按钮,校验
  formSubmit: function (e) {
    //防止重复点击或者点击过快
    console.log("点击了");
    if (!isClick) {
      console.log("重复返回~");
      return;
    }
    if (isClick) {
      isClick = false;
      //定时器
      setTimeout(function () {
        isClick = true;
      }, 5000); //3秒内不能重复点击
    }
    let userName = e.detail.value.userName;
    let phone = e.detail.value.phone;
    let detailAddress = e.detail.value.detailAddress;
    if (userName.trim() == "") {
      wx.showToast({
        title: '请输入收件人姓名',
        icon: 'none'
      })
      return;
    }
    if (phone.trim() == "") {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      })
      return;
    }

    let a = /^1\d{10}$/;
    if (!a.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      })
      return;
    }
    if (this.data.address == '请选择地区：') {
      wx.showToast({
        title: '请选择地区',
        icon: 'none'
      })
      return;
    }
    if (detailAddress.trim() == "") {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return;
    }
    this.setData({
      formValue: e.detail.value
    })
    let materialInfo = {};
    materialInfo['receiveProvinceId'] = addressInfo.receiveProvinceId;
    materialInfo['receiveCityId'] = addressInfo.receiveCityId;
    materialInfo['receivceDistrictId'] = addressInfo.receivceDistrictId;
    materialInfo['receiveProvinceName'] = addressInfo.receiveProvinceName;
    materialInfo['receiveCityName'] = addressInfo.receiveCityName;
    materialInfo['receiveDistrictName'] = addressInfo.receiveDistrictName;
    materialInfo['receiveName'] = userName;
    materialInfo['receivePhone'] = phone;
    materialInfo['receiveAddress'] = detailAddress;
    wx.setStorageSync('materialInfo', materialInfo)
    if (this.data.type != 'updateMatter') { //正常流程领奖，填写信息
      this.revicePrize();
    } else { //修改信息
      // this.updateMatter();
    }
  },
  updateMatter: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    //防止重复点击或者点击过快
    console.log("点击了");
    if (!isClick) {
      console.log("重复返回~");
      return;
    }
    if (isClick) {
      isClick = false;
      //定时器
      setTimeout(function () {
        isClick = true;
      }, 5000); //3秒内不能重复点击
    }
    this.isLoading(true, "正在提交...");
    const that = this;
    //兑奖
    netWork.POST('xhtx/little/updateMatter', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: that.data.prizeOrderId,
        receiveName: that.data.formValue.userName, //收货人
        receivePhone: that.data.formValue.phone, //收货电话
        receiveProvinceId: addressInfo.receiveProvinceId, //省
        receiveCityId: addressInfo.receiveCityId, //市
        receivceDistrictId: addressInfo.receivceDistrictId, //区
        receiveProvinceName: addressInfo.receiveProvinceName,
        receiveCityName: addressInfo.receiveCityName,
        receiveDistrictName: addressInfo.receiveDistrictName,
        receiveAddress: that.data.formValue.detailAddress, //地址
      },
      success: function (res) {
        that.isLoading(false);
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {


          that.handlerGobackClick();
        } else if (res.data.retCode == "10052") {
          setTimeout(function () {
            wx.showToast({
              title: '收货信息不支持表情等特殊字符，请修改后再提交哦~',
              icon: 'none',
              duration: 3000
            })
          }, 100)
        } else {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          })
        }

      },
      fail: function () {
        that.isLoading(false);
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
        })
      }
    });
  },
  /**
   * 显示活动规则
   */
  showRule: function () {
    wx.navigateTo({
      url: '../ruleh5/ruleh5?productType='+this.data.productType
    })
  },
  /**
   * 关闭活动规则
   */
  clickClose: function () {
    this.setData({
      ani: 1
    })
    const that = this;
    setTimeout(function () {
      that.setData({
        isShowModalRule: false
      })
    }, 180);
  },
  adressMsg: function (event) {
    console.log(JSON.stringify(event.detail.value))
    if (event.detail.value != "" || event.detail.value != null) {
      this.setData({
        addressMsg: event.detail.value
      })
    }

  },
  /**
   * 勾选实物
   * @param {*} e 
   */
  onclick: function (e) {
    var arr = this.data.chooseList; //声明的数组
    var index = e.currentTarget.dataset.index; //当前数组的索引下标
    for (var item in arr) {
      if (item == index) {
        arr[item].status = true;
        //把选中的奖品存在data
        this.setData({
          prizeOrderId: arr[item].prizeOrderId,
          prizeId: arr[item].prizeId
        })
        //把选中的奖品存在data
        this.setData({
          choosePrize: arr[item]
        })
      } else {
        arr[item].status = false;
      }
    }
    this.setData({
      chooseList: arr
    })
  },
  /**
   * 判断是否选择奖品
   */
  checkChoose: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if (this.data.choosePrize == "") {
      setTimeout(function () {
        wx.showToast({
          title: '请勾选您想要领取的奖品',
          icon: 'none',
          duration: 2500
        })
      }, 500);
    } else {
      this.setData({
        isShowSelectPrize: false
      })
    }
  },
  handlerGobackClick() {
    wx.navigateBack({
      delta: 1
    });
  },
  isLoading(isLoading, loadingText) {
    this.setData({
      isLoading: isLoading,
      loadingText: loadingText
    })

  },
  onShow(){
    try {
        if (wx.onNeedPrivacyAuthorization) {
            wx.onNeedPrivacyAuthorization(resolve => {
                this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                this.resolvePrivacyAuthorization = resolve
            })
        }
    } catch (error) {
        console.info(error)
    }
  }

})